package com.alit.mongodb.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.alit.mongodb.doc.Page;
import com.alit.mongodb.doc.UserBo;
import com.mongodb.WriteResult;

@Repository
public class MongoDaoImpl implements IMongoDao<UserBo> {

  @Autowired
  private MongoTemplate template;

  public List<UserBo> find(Query query) {
    List<UserBo> userList = template.find(query, UserBo.class);
    return userList;
  }

  public UserBo findOne(Query query) {
    UserBo userBo = template.findOne(query, UserBo.class);
    return userBo;
  }

  public void save(UserBo entity) {
    template.save(entity);
  }

  public WriteResult update(Query query, Update update) {
    if (update == null) {
      return null;
    }
    WriteResult writeResult = template.updateMulti(query, update, UserBo.class);
    return writeResult;
  }

  public List<UserBo> findAll(String collectionName) {
    return template.findAll(UserBo.class, collectionName);
  }

  public long count(Query query) {
    long count = template.count(query, "userBo");
    return count;
  }

  public WriteResult remove(Query query) {
    WriteResult remove = template.remove(query, "userBo");
    return remove;
  }

  public Page<UserBo> findPage(Page<UserBo> page, Query query) {
    query = query == null ? new Query(Criteria.where("_id").exists(true)) : query;
    long count = this.count(query);
    // ����
    page.setTotalCount((int) count);
    int currentPage = page.getCurrentPage();
    int pageSize = page.getPageSize();
    query.skip((currentPage - 1) * pageSize).limit(pageSize);
    List<UserBo> rows = this.find(query);
    page.build(rows);
    return page;
  }
}
